package la.iok.hzsvn.lewin.movie.service;

import la.iok.hzsvn.lewin.movie.config.RedisKey;
import la.iok.hzsvn.lewin.movie.core.Token;
import la.iok.hzsvn.lewin.movie.core.exception.ErrorCode;
import la.iok.hzsvn.redis.service.RedisService;
import la.iok.hzsvn.share.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class MovieDownloadServiceImpl implements MovieDownloadService{
    private final RedisKey redisKey;
    private final RedisService redisService;

    public MovieDownloadServiceImpl(RedisKey redisKey, RedisService redisService) {
        this.redisKey = redisKey;
        this.redisService = redisService;
    }

    @Override
    public void saveDownloadMovie(@NotNull Token token, @NotNull Long movieId, @NotNull Long movieInstanceId) {
        String key = redisKey.movieDownloadKey(token,movieId);
        redisService.set(key,movieInstanceId);
        redisService.expire(key,60, TimeUnit.MINUTES);
    }

    public Long loadDownloadInstance(@NotNull Token token, @NotNull Long movieId){
        Long instanceId = (Long) redisService.get(redisKey.movieDownloadKey(token,movieId));
        ErrorCode.DOWNLOAD_INSTANCE_NOT_EXIST.assertNotNull(instanceId);
        return instanceId;
    }
}
